package com.antjupt.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Wizarder
 * @create 2021-05-25 12:11
 */
public class HelloServlet2 extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);//在其他方法中用getServletConfig时候需要在初始化调用super.init(config)因为HttpServlet父类
        // GenericServlet里面的这方法需要给自己定义private transient ServletConfig config;赋值,如果不调用就会出现异常
        System.out.println("重写了init方法做了一些工作");
    }

    /**
     *
     * @param req 做get请求方式
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HttpServlet中的doGet");
    }

    /**
     *
     * @param req 做post请求方式
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletConfig servletConfig = getServletConfig();
        //1获取servlet的名字
        String servletName = servletConfig.getServletName();
        System.out.println(servletName);
        //2获取init-param
        String username = servletConfig.getInitParameter("username");
        System.out.println("username = " + username);
        //3获取servletContext
        ServletContext servletContext = servletConfig.getServletContext();
        System.out.println(servletContext);

        System.out.println("HttpSevlet中的doPost");
    }
}
